package com.mk.common.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;


import org.junit.Test;

/**
 * 栈
 * @author 上官雅晴
 *
 */
public class StackDemo {

	@Test
	public void test1() {
		Stack<String> stack = new Stack<>();
		stack.push("2");
		stack.push("3");
		
		System.out.println(stack.peek());
	}
	
	
	/**
	 * 后缀表达式的操作运算
	 */
	@Test
	public void test2() {
		// 2 + 1 * 4 + 5 - 2 = 9, 中序遍历/中缀表达式
		String[] arr = {"2","1","4","*","+","5","+","2","-"};
		int m,n; //两个运算数
		int calcResult = 0; //两个运算数的运算结果
		//运算符: +, -, *, /
		List<String> operators = new ArrayList<>(4);
		operators.add("+");
		operators.add("-");
		operators.add("*");
		operators.add("/");
		//操作栈
		Stack<Integer> opStack = new Stack<>();
		for(String str: arr) {
			if(!operators.contains(str)) {
				//不是运算符，视为运算数
				opStack.push(Integer.parseInt(str));
				continue;
			}
			
			//若为运算符
			if(opStack.empty()  ) {
				continue;
			}
			n = opStack.pop(); //后
			m = opStack.pop(); //前
			
			if("+".equals(str)) { //加法运算
				calcResult = m + n;
			}
			if("-".equals(str)) { //减法运算
				calcResult = m - n;
			}
			if("*".equals(str)) { //乘法运算
				calcResult = m * n;
			}
			if("/".equals(str)) { //除法运算
				calcResult = m / n;
			}
			//压入操作栈
			opStack.push(calcResult);
		}
	
		
		//输出结果
		System.out.println( opStack.peek() );
	}
	
	
	
	
	
}
